<?
    require_once("config.php");
    
    $menu = new Menu("Guest Functions");
    $menu->AddItem(new MenuItem("Guest Login","login.php?method=guest", AuthConstants::NOT_LOGGED_IN));
    $menu->AddItem(new MenuItem("View Listings","listings.php", AuthConstants::ALL_LOGGED_IN));
    MenuManager::AddMenu("Request Guest Account",$menu);
    
    if ($_POST) {
        if ($_POST['num1'] + $_POST['num2'] == $_POST['result']) {
            if (!$_POST['name'] || !$_POST['email']) header("Location: guest.php?error=invalid" . ($_POST['type'] == "landlord" ? "&type=landlord" : ""));
            else {
                $query = "SELECT * FROM guests WHERE email LIKE '$_POST[email]';";
                if (DBM::CountRows($query) > 0 && !isset($_POST['id'])) {
                    header("Location: guest.php?error=bademail");
                    exit;
                }
                
                $build = array();
                $tmppassword = substr(md5(microtime()),0,8);    // save this here for the notification
                $build['name'] = $_POST['name'];
                $build['email'] = $_POST['email'];
                if (isset($_POST['rin'])) {
                    $build['rin'] = $_POST['rin'];
                }
                
                // don't update the password unless we're supposed to
                if ($_POST['newpassword'] || !isset($_POST['guestpassword'])) {
                    $build['password'] = md5($tmppassword);
                    $build['password_plaintext'] = $tmppassword;
                }
                else if ($_POST['guestpassword']) {
                    if ($_POST['guestpassword'] != $_POST['guestpassword2']) {
                        header("Location: guest.php?err=passwords");
                        exit;
                    }
                    $build['password'] = md5($_POST['guestpassword']);
                    $build['password_plaintext'] = $_POST['guestpassword'];
                }
                    
                $build['created'] = time();
                $build['expires'] = time() + (60*60*24 * (is_numeric($_POST['days_valid']) ? $_POST['days_valid'] : SettingManager::GetSetting("guest accounts valid for")));       // enable the account for 90 days
                
                // If an administrator is requesting the account then auto approve
                if (AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS)) {
                    $build['approved'] = 1;
                    $build['override_auth'] = $_POST['override_auth'];
                    if ($_POST['days_valid'] == "0") $build['expires'] = 0;
                }
                else if ($_POST['type'] == "landlord") {
                    // verify that they agreed to everything.
                    if (!(
                        isset($_POST['tos_chk']) &&
                        isset($_POST['privacy_chk']) && 
                        isset($_POST['fairhousing_chk']) &&
                        isset($_POST['agree_chk'])
                        )) {
                        header("Location:guest.php?type=landlord&error=noagree");
                        exit;
                    }
                    
                    
                    $build['override_auth'] = 3;    // landlord    
                    $build['expires'] = 0;          // landlord accounts shouldn't expire
                }

                if ($build['override_auth'] <= 0) $build['override_auth'] = 1;
                
                // Run the query
                $query = '';
                if ($_POST['id'] && AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS))
                    $query = QueryTools::CreateQuery($build,"guests","update",$_POST['id']);
                else
                    $query = QueryTools::CreateQuery($build,"guests");

                DBM::Query($query);
                
                // notify the administrators if necessary
                if (!AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS)) {
                    $id = ($_POST['id'] ? $_POST['id'] : DBM::LastInsertID());
                    MailManager::SendGuestAccountRequest($id);
                }
                header("Location: guest.php?action=confirmed&name=$_POST[name]" . (AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS) ? "&password=$build[password_plaintext]" : ""));
            }
        }
        else {
            die();
        }
    }   
    else if ($_GET['action'] == 'checkemail') {
        $query = "SELECT * FROM guests WHERE email LIKE '$_GET[email]';";
        echo DBM::CountRows($query);
        exit;
    }
    else if ($_GET['action'] == 'confirmed') {
        Functions::PrintHeader("Request Guest Account");
        SuccessMessage::Show("Request Received","Your account request has been received.  
                                                You should expect verification within one or two 
                                                business days.<br><br>Click 
                                                <a href='index.php'>Here</a> to return 
                                                to the main page." . (AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS) ? "<br><br>Your password is $_GET[password]" : ""));
        Functions::PrintFooter();
    }
    else {
        Functions::PrintHeader("Request Guest Account");
        
        if ($_GET['error'] == "passwords") {
            ErrorMessage::Show("Invalid Passwords","The passwords you specified didn't match.  Please try again.");
        }
        if ($_GET['error'] == "invalid") {
            ErrorMessage::Show("Invalid Name/E-Mail","You need to specify both a Name and E-Mail address.");
        }
        if ($_GET['error'] == "noagree") {
            ErrorMessage::Show("Error Requesting","You did not agree to one or more of the conditions listed below.  You must agree to ALL of these conditions in order to gain landlord access in our system.");
        }
        if ($_GET['error'] == "bademail") {
            ErrorMessage::Show("Sorry","That E-Mail address is already in our system.  Have you <a href='changepassword.php?action=forgot'>forgotten your password?</a>.");
        }
        ?>
        <script type='text/javascript'>
            window.onload = function() {
                $("result").value = $("num1").value * 1 + $("num2").value * 1;
            };
        </script>
        <form method="POST" action='guest.php'>
            <?
                $data = null;
                if ($_GET['id'] && AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS)) {
                    $data = DBM::FetchRow("SELECT * FROM guests WHERE id=$_GET[id];");
                    echo "<input type='hidden' name='id' value='$_GET[id]' />";
                }
            ?>
            <table align='center' class='cgltable'>
            <thead>
                <tr>
                    <th colspan='2'>Request <?=(isset($_GET['type']) && $_GET['type'] == "landlord" ? "Landlord" : "Guest")?> Account</th>
                </tr>
                </thead>
                <tr>
                    <td class='label'>Name: </td>
                    <td><input type='text' name='name' value="<?=$data['name']?>" /></td>
                </tr>
                <tr>
                    <td class='label'>
                        E-Mail Address<br />
                    </td>
                    <td>
                        <input type='text' name='email' id='email' value="<?=$data['email']?>" /><br />
                        <span style='font-size:8pt;'>
                            A <b>valid</b> E-Mail address is <b>required</b> to use the system. <br />
                            Failure to provide an accurate E-Mail address may result in the cancellation <br />
                            of your request.  With no E-Mail we have no way of notifying you of this.
                        </span>
                    </td>
                </tr>
                <? if (AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS)) { ?>
                <tr>
                    <td class='label'>Password</td>
                    <td>
                        <label><input type='checkbox' name='newpassword' <?=(!$data ? "checked" : "")?> />Auto-Generate</label>
                        <br>
                        <input type='password' name='guestpassword' /><br>
                    </td>
                </tr>
                <tr>
                    <td class='label'>Re-Type Password</td>
                    <td>
                        <input type='password' name='guestpassword2' />
                    </td>
                </tr>
                <tr>
                    <td class='label'>Override Account Permissions:</td>
                    <td>
                        <label><input type='radio' name='override_auth' value='1' <?=($data['override_auth'] == 1 || !$data ? 'checked ' : '')?>/>Guest</label><br>
                        <label><input type='radio' name='override_auth' value='2' <?=($data['override_auth'] == 2 ? 'checked ' : '')?>/>Student</label><br>
                        <label><input type='radio' name='override_auth' value='3' <?=($data['override_auth'] == 3 ? 'checked ' : '')?>/>Landlord</label><br>
                        <label><input type='radio' name='override_auth' value='4' <?=($data['override_auth'] == 4 ? 'checked ' : '')?>/>Administrator</label><br>
                    </td>
                </tr>   
                <tr>
                    <td class='label'>Override Account Time Valid:</td>
                    <?
                        // find out what to put in the guest account box
                        $value = SettingManager::GetSetting("guest accounts valid for");
                        if ($data) {
                            if ($data['expires'] > 0) {
                                $value = ($data['expires'] - $data['created']) / (60*60*24);
                            }
                            else $value = 0;
                        }
                    ?>
                    <td><input type='text' name='days_valid' value="<?=$value?>" /> Days<br><span style='font-size:7pt;'>Enter 0 for no expiration</span></td>
                </tr>
                <? 
                } else { 
                    if ($_GET['type'] == "landlord") {
                        echo "<input type='hidden' name='type' value='landlord' />";
                        ?>
                        <tr>
                            <td colspan='2'>
                                <span style='color:green; font-weight:bold;'>If you already have an account in the old system, you can <a href='migrate.php'>migrate it to the new system here</a>.</span><hr />
                                
                                To register for a landlord account, you must agree to:
                                <ul>
                                    <li><a target="_blank" href='tos.php'>The Terms of Service</a></li>
                                    <li><a target="_blank" href='privacy.php'>The Privacy Statement</a></li>
                                    <li><a target="_blank" href='fairhousing.php'>The Fair and Equal Housing Policy</a></li>
                                </ul>
                                <label><input type='checkbox' id='tos_chk' name='tos_chk' /> I have read and agree to the Terms of Service Agreement</label><br />
                                <label><input type='checkbox' id='privacy_chk' name='privacy_chk' /> I have read and agree to the terms as outlined in the Privacy Statement.</label><br />
                                <label><input type='checkbox' id='fairhousing_chk' name='fairhousing_chk' /> I have read the agree to the Fair and Equal Housing Opportunity Policy.</label><br />
                                <label><input type='checkbox' id='agree_chk' name='agree_chk' /> 
                                    I agree that any infractions of the policies as outlined in the above documents will <br />
                                    result in my removal (at the sole discretion of the Rensselaer Union) from the system <br />
                                    without question or right to appeal.</label>
                            </td>
                        </tr>
                        <?php
                    }
                    else {
                        echo "<tr><td class='label'>Situation:</td>";
                        echo "<td><textarea name='rin'></textarea><br />";
                        echo "<span style='font-size:8pt;'>Please (briefly) explain your situation.<br />";
                        echo "Include your RIN if you know it (as this greatly expedites the process), <br />";
                        echo "otherwise, include your research supervisor or some other member of the <br />";
                        echo "RPI community that we can use to validate your need for housing.";
                        echo "</td></tr>";
                    }
                } 
                ?>
                <tfoot>
                <tr>
                    <td colspan='2'><input type='reset' value='Start Over' /><input type='submit' id='submitbutton' value='Request Account' /></td>
                </tr>
                </tfoot>
            </table>
            
            <!-- Protect against bots without user interaction -->
            <!-- uses javascript to add num1 and num2 -->
            <input type='hidden' name='num1' id='num1' value="<?=rand(0,100)?>" />
            <input type='hidden' name='num2' id='num2' value="<?=rand(0,100)?>" />
            <input type='hidden' name='result' id='result' />
        </form>
        <?
        Functions::PrintFooter();
    }
?>
